package com.gooluke.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gooluke.auth.dao.RoleDao;
import com.gooluke.auth.dao.UserDao;
import com.gooluke.auth.dao.UserRoleDao;
import com.gooluke.auth.dto.UserDto;
import com.gooluke.auth.entity.SysRole;
import com.gooluke.auth.entity.SysUser;
import com.gooluke.auth.entity.SysUserRole;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleDao roleDao;

    public UserDto selectByBasicUserInfo(String userId) {
        SysUser user = userDao.getBaseMapper().selectOne(new QueryWrapper<SysUser>().eq("user_id", userId));
        if (user == null) {
            return null;
        }
        // 获取用户角色信息，这里是以用户数据id和权限关联，不是用户自定义id
        List<SysUserRole> userRoles = userRoleDao.getBaseMapper().selectList(new QueryWrapper<SysUserRole>().eq("user_id", user.getId()));
        if (CollectionUtils.isEmpty(userRoles)) {
            userRoles = Collections.emptyList();
        }
        List<Long> roleIds = userRoles.stream().map(SysUserRole::getRoleId).toList();
        List<SysRole> roles = roleDao.getBaseMapper().selectList(new QueryWrapper<SysRole>().in("role_id", roleIds));
        UserDto userDto = new UserDto();
        userDto.setUserId(user.getUserId());
        userDto.setUsername(user.getUsername());
        userDto.setPassword(user.getPassword());
        userDto.setRoles(roles.stream().map(SysRole::getRoleCode).toList());
        return userDto;
    }
}
